// Copyright (c) 2019 Presto Labs Pte. Ltd.
// Author: jaewon

#include "coin1/fastfeed/view/string_json_builder.h"

#include <glog/logging.h>

#include "coin1/base/exception_util.h"

namespace fastfeed {
namespace view {

bool StringJsonBuilder::UpdateByProto(const proto::Feed& feed) {
  if (feed.data_type() != proto::DATA_TYPE_STRING && feed.data_type() != proto::DATA_TYPE_JSON) {
    LOG(ERROR) << "Unsupported data type:" << feed.data_type();
    return false;
  }

  UpdateHeader(feed);
  feed_ = &feed;

  if (feed.data_type() == proto::DATA_TYPE_JSON) {
    json_obj_ = nlohmann::json::parse(feed.json());
  }
  return true;
}

const nlohmann::json& StringJsonBuilder::json_object() const {
  DCHECK_EQ_THROW(data_type(), proto::DATA_TYPE_JSON, std::invalid_argument);
  return json_obj_;
}

const std::string& StringJsonBuilder::string() const {
  switch (data_type()) {
    case proto::DATA_TYPE_STRING:
      return feed_->string();

    case proto::DATA_TYPE_JSON:
      return feed_->json();

    default:
      LOG(FATAL) << "Not reached.";
  }
}

}  // namespace view
}  // namespace fastfeed
